//  this library.
import 'package:flutter/material.dart';
import 'package:hktk_app/dao/course_dao.dart';
import 'package:hktk_app/exception/dao_exception.dart';
import 'package:hktk_app/ienum/my/up_load_enum.dart';
import 'package:hktk_app/model/course/note_video_model.dart';
import 'package:hktk_app/model/page/resource_page_model.dart';
import 'package:hktk_app/util/font_util.dart';
import 'package:hktk_app/util/toast_util.dart';
import 'package:hktk_app/util/view_util.dart';
import 'package:hktk_app/widget/course/note_title_widget.dart';
import 'package:hktk_app/widget/question/note_item_widget.dart';

/// 课程详情笔记显示页面
class NoteCoursePage extends StatefulWidget {
  /// 章节id
  final String chapterId;

  /// 章节名称
  final String chapterName;

  /// 视频id
  final String videoId;

  const NoteCoursePage({
    super.key,
    required this.chapterId,
    required this.chapterName,
    required this.videoId,
  });

  @override
  State<NoteCoursePage> createState() => _NoteCoursePageState();
}

class _NoteCoursePageState extends State<NoteCoursePage> {
  late BuildContext _context;

  /// 初始化数据方法
  late Future<Map<String, dynamic>> _futureInit;

  /// 相关数据
  late List<NoteVideoModel> _list;

  /// 页数
  late int _current;

  /// 条数
  late int _size;

  /// 列表滑动控制器
  late ScrollController _scrollController;

  /// 加载中，
  late bool _loading;

  /// 加载状态，0：什么都不显示，1：表示加载中，2：表示没有数据了
  late UploadEnum _loadType;

  @override
  void initState() {
    super.initState();
    debugPrint("noteCoursePage 页面 -> initState 方法执行 ===> ");
    debugPrint("");
    _current = 1;
    _size = 10;
    _loading = false;
    _loadType = UploadEnum.loading;
    _list = [];
    _futureInit = _initData();
    _scrollController = ScrollController();

    // 监听是否滑动到底部，实现上拉加载功能
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        debugPrint("noteCoursePage 页面 -> 滑动到底部 ===> 上拉加载更多数据");
        if (_loadType != UploadEnum.noData) {
          _loadDataInit();
        }
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    debugPrint("noteCoursePage 页面 -> dispose 方法执行 ===> ");
    debugPrint("");
    _scrollController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    debugPrint("noteCoursePage 页面 -> build 方法执行 ===> ");
    debugPrint("");
    _context = context;
    return Container(
      padding: EdgeInsets.all(24),
      child: Column(
        children: [
          _titleItem(),
          hiSpace(height: 32),
          Expanded(child: _futureItem()),
        ],
      ),
    );
  }

  /// 初始化数据方法
  Future<Map<String, dynamic>> _initData() async {
    Map<String, dynamic> map = {};
    try {
      ResourcePageModel<NoteVideoModel> page = await CourseDao.notePageList(
        current: _current,
        size: _size,
      );
      // 判断上滑加载方法
      if (!_loading) {
        // 第一次默认加载
        _list = page.records ?? [];
        if (_list.length < _size) {
          _loadType = UploadEnum.def;
        }
      } else {
        // 上滑加载更多
        List<NoteVideoModel> list = page.records ?? [];
        _list.addAll(list);
        // 大于总数说明没有多的数据了
        int total = page.total ?? 0;
        if (_list.length >= total) {
          _loadType = UploadEnum.noData;
        }
      }
      map["suc"] = true;
    } catch (e) {
      debugPrint("noteCoursePage 页面 -> 初始化数据发生异常 ===> $e");
      map = {"suc": false, "msg": "未知错误，请重试"};
      if (e is DaoException) {
        debugPrint("noteCoursePage 页面 -> dao异常 ===> ${e.msg}");
        map["msg"] = e.msg;
      }
    }
    return map;
  }

  /// 上拉加载更多数据执行方法
  void _loadDataInit() {
    debugPrint("noteCoursePage 页面 -> 上拉加载更多 ===> $_loading");
    if (_loadType == UploadEnum.def) {
      setState(() {
        _loadType = UploadEnum.noData;
      });
    } else if (_loadType == UploadEnum.loading) {
      if (!_loading) {
        // 重新加载数据
        _current++;
        _loading = true;
        _initData().then((Map<String, dynamic> map) {
          if (!map['suc']) {
            ToastUtil.show(context: _context, msg: map["msg"]);
          }
          setState(() {
            _loading = false;
          });
        });
      }
    }
  }

  /// 标题，记笔记显示
  _titleItem() {
    return NoteTitleWidget(
      relationId: widget.chapterId,
      relationName: widget.chapterName,
      videoId: widget.videoId,
    );
  }

  /// 异步加载组件
  _futureItem() {
    return FutureBuilder<Map<String, dynamic>>(
      future: _futureInit,
      builder: (
          BuildContext context,
          AsyncSnapshot<Map<String, dynamic>> snapshot,
          ) {
        if (snapshot.connectionState == ConnectionState.done) {
          Map<String, dynamic> map = snapshot.data!;
          if (!map["suc"]) {
            WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
              ToastUtil.show(context: context, msg: map["msg"]);
            });
          }
          return _content();
        } else {
          return const Center(
            child: CircularProgressIndicator(),
          );
        }
      },
    );
  }

  /// 内容显示组件
  _content() {
    if (_list.isNotEmpty) {
      return MediaQuery.removePadding(
        removeTop: true,
        context: _context,
        child: ListView.separated(
          itemBuilder: _itemBuilder,
          separatorBuilder: _separatorBuilder,
          itemCount: _list.length + 1,
          controller: _scrollController,
        ),
      );
    } else {
      return showNoData();
    }
  }

  /// 笔记内容显示
  Widget? _itemBuilder(BuildContext context, int index) {
    if (index < _list.length) {
      NoteVideoModel model = _list[index];
      return NoteItemWidget(
        createName: model.createName,
        createHeader: model.createHeader,
        content: model.content,
        contentStyle: FontUtil.fontBlack1(30),
      );
    } else {
      return _tipsItem();
    }
  }

  /// 间距显示
  Widget _separatorBuilder(BuildContext context, int index) {
    return hiSpace(width: 20);
  }

  /// 提示组件
  Widget? _tipsItem() {
    if (_loadType == UploadEnum.def) {
      return null;
    } else if (_loadType == UploadEnum.loading) {
      return SizedBox(
        height: 100,
        child: Center(
          child: SizedBox(
            width: 40,
            height: 40,
            child: CircularProgressIndicator(
              strokeWidth: 4,
            ),
          ),
        ),
      );
    } else if (_loadType == UploadEnum.noData) {
      return showListEnd();
    }
    return null;
  }
}
